<template>
    <main>
        <div class="chart-container">
            <div class="chart-wrapper">
                <div ref="barChart" class="chart" style="width: 100%; height: 400px;"></div>
            </div>
            <div class="chart-wrapper">
                <div ref="lineChart" class="chart" style="width: 100%; height: 400px;"></div>
            </div>
            <div class="chart-wrapper">
                <div ref="pieChart" class="chart" style="width: 100%; height: 400px;"></div>
            </div>
        </div>
    </main>
</template>

<script>
import * as echarts from 'echarts';

export default {
    name: 'HomeView',
    data() {
        return {
            barChart: null,
            lineChart: null,
            pieChart: null
        }
    },
    mounted() {
        this.initCharts();
    },
    methods: {
        async initCharts() {
            await this.initBarChart();
            await this.initLineChart();
            await this.initPieChart();
        },
        async initBarChart() {
            try {
                const response = await this.$axios.get('/api/chart/monthly-sales');
                const data = response.data;

                const chartDom = this.$refs.barChart;
                this.barChart = echarts.init(chartDom);

                const option = {
                    title: {
                        text: '月度销售额',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    legend: {
                        data: data.series.map(item => item.name),
                        top: '10%'
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: data.months,
                        axisLabel: {
                            rotate: 45
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: '销售额 (万元)'
                    },
                    series: data.series.map(item => ({
                        name: item.name,
                        type: 'bar',
                        data: item.data,
                        itemStyle: {
                            color: item.color
                        }
                    }))
                };

                this.barChart.setOption(option);

                window.addEventListener('resize', () => {
                    this.barChart.resize();
                });
            } catch (error) {
                console.error('Error fetching monthly sales data:', error);
            }
        },
        async initLineChart() {
            try {
                const response = await this.$axios.get('/api/chart/user-growth');
                const data = response.data;

                const chartDom = this.$refs.lineChart;
                this.lineChart = echarts.init(chartDom);

                const option = {
                    title: {
                        text: '用户增长趋势',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: data.series.map(item => item.name),
                        top: '10%'
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: data.days
                    },
                    yAxis: {
                        type: 'value',
                        name: '用户数'
                    },
                    series: data.series.map(item => ({
                        name: item.name,
                        type: 'line',
                        data: item.data,
                        smooth: true,
                        itemStyle: {
                            color: item.color
                        },
                        areaStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {
                                    offset: 0,
                                    color: this.hexToRgba(item.color, 0.5)
                                },
                                {
                                    offset: 1,
                                    color: this.hexToRgba(item.color, 0.1)
                                }
                            ])
                        }
                    }))
                };

                this.lineChart.setOption(option);

                window.addEventListener('resize', () => {
                    this.lineChart.resize();
                });
            } catch (error) {
                console.error('Error fetching user growth data:', error);
            }
        },
        async initPieChart() {
            try {
                const response = await this.$axios.get('/api/chart/product-sales');
                const data = response.data;

                const chartDom = this.$refs.pieChart;
                this.pieChart = echarts.init(chartDom);

                const option = {
                    title: {
                        text: '产品销量占比',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                        top: '15%'
                    },
                    series: [
                        {
                            name: '销量占比',
                            type: 'pie',
                            radius: ['40%', '70%'],
                            avoidLabelOverlap: false,
                            itemStyle: {
                                borderRadius: 10,
                                borderColor: '#fff',
                                borderWidth: 2
                            },
                            label: {
                                show: false,
                                position: 'center'
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: '18',
                                    fontWeight: 'bold'
                                }
                            },
                            labelLine: {
                                show: false
                            },
                            data: data.map(item => ({
                                value: item.value,
                                name: item.name,
                                itemStyle: {
                                    color: item.color
                                }
                            }))
                        }
                    ]
                };

                this.pieChart.setOption(option);

                window.addEventListener('resize', () => {
                    this.pieChart.resize();
                });
            } catch (error) {
                console.error('Error fetching product sales data:', error);
            }
        },
        hexToRgba(hex, opacity) {
            // 转换十六进制颜色为RGBA格式
            let r = parseInt(hex.slice(1, 3), 16);
            let g = parseInt(hex.slice(3, 5), 16);
            let b = parseInt(hex.slice(5, 7), 16);
            return `rgba(${r}, ${g}, ${b}, ${opacity})`;
        }
    },
    beforeDestroy() {
        // 组件销毁时移除事件监听和图表实例
        window.removeEventListener('resize', this.resizeHandler);
        if (this.barChart) {
            this.barChart.dispose();
        }
        if (this.lineChart) {
            this.lineChart.dispose();
        }
        if (this.pieChart) {
            this.pieChart.dispose();
        }
    }
}
</script>

<style scoped>
.chart-container {
    display: flex;
    flex-direction: column;
    gap: 30px;
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

.chart-wrapper {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
}

@media (min-width: 992px) {
    .chart-container {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
    }

    .chart-wrapper:last-child {
        grid-column: span 2;
    }
}
</style>